<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 15-6-23
 * Time: 上午9:18
 */
namespace Admin\Controller;
use Admin\Model\UserModel;
use Think\Controller;
use User\Api\UserApi;
class UserController extends AdminController{
    /*
     * 用户首页
     */
    public function index(){
        $User = M('User');
        $list = $this->lists($User);
        $this->assign('list', $list);
        $this->display();
    }

    /*
     *用户添加
     */
    public function add($username='', $password='', $repassword='',$email=''){
        if(IS_POST){
            if($password != $repassword){
                $this->errror("密码和重复密码不一样");
            }
            $User = new UserApi();
            $uid = $User->register($username, $password,$email);
            if(0<$uid){
                $this->success('添加用户成功',U('User/index'));
            }else{
                $this->error('添加用户失败');
            }
        }else{
            $this->meta_title = '新增用户';
            $this->display();
        }
    }
    /*
     * 机构用户添加
     */
    public function unitAdd(){
        if(IS_AJAX){
            $data = I('post.');
            $User = new UserApi();
            $uid = $User->register($data['username'],"123456",$data['email']);
            if(0<$uid){
                $department = M('User')->where('id='.UID)->getField('department');
                $array = array(
                    'department'=>$department
                );
                $User->updateInfo($uid,$array);
                if($res=$this->addGroup($uid,'5')){
                    $this->success('用户添加成功',U('Unit/user'));
                }
                    $this->error('用户没有添加进用户组');
            }else{
                $this->error('用户添加失败');
            }
        }
        $this->display();
    }

    /*
     *机构用户删除
     */
    public function unitDel($uid='',$department=''){
        //判断这个用户是否属于这个机构
        $data = I('get.');
        $condition = M('User')->where($data)->getField(id);
        if($condition){
            //删除这个用户
            $res = D('User')->where($data )->delete();
            if($res){
               $this->success('成功删除用户',U('Unit/user'));
            }else{
                $this->error('对不起，未知原因删除用户');
            }
        }else{
            $this->error('对不起用户不属于您管理的用户');exit;
        }

    }

    /*
     * 修改用户状态
     */
    public function changeStatus($method = null){
        $id = I('get.id',0);
        if(1==$id){
            $this->error("不允许对超级管理员进行操作");
        }
        $map['id'] = $id;
        switch($method){
            case 'forbidUser':
                $this->forbid('User',$map);
                break;
            case 'resumeUser';
                $this->resume('User',$map);
                break;
            case 'deleteUser':
                $this->delete('User',$map);
                break;
            default:
                $this->error('参数非法');
        }
    }
    //用户行为日志
    public function action(){
        $data = I('get.');
        $where = array();
        if(empty($data['username']) === false){
            $uid = $this->getUidByUsername($data['username']);
            $where['user_id'] = $uid;
        }
        if(empty($data['action']) === false){
            switch($data['type']){
                case "1":
                    $where['action'] = array('LIKE','用户登录');
                    break;
                case "2":
                    $where['action'] = array('LIKE','退出系统');
                    break;
            }
        }
        $Log = M('Log'); // 实例化User对象
        if(empty($where)){
            $list = $this->lists($Log);
        }else{
            $list = $this->lists($Log,$where);
        }
        $this->assign('_list',$list);// 赋值数据集s
        $this->display(); // 输出模板
    }

    //用户业务操作
    public function actionlog(){
        $data = I('get.');
        $where = array();
        if(empty($data['username']) === false){
            $uid = $this->getUidByUsername($data['username']);
            if($uid===null){
                $where['user_id'] = '';
//                $this->error('对不起！用户名不存在');
            }else{
                $where['user_id'] = $uid;
            }
        }
        if(empty($data['action_id'])===false){
            $where['action_id'] = $data['action_id'];
        }
        $Log = M('ActionLog'); // 实例化User对象
        if(empty($where)){
            $list = $this->lists($Log);
        }else{
            $list = $this->lists($Log,$where);
        }
        $this->assign('search',$data);
        $this->assign('_list',$list);// 赋值数据集
        $this->meta_title = '日志';
        if(isset($_GET['p'])){
            $num = ($_GET['p']-1)*10;
            $this->assign('num', $num);
        }
        $this->display(); // 输出模板
    }

    private function addGroup($uid,$groupId){
        return D('AuthGroupAccess')->addGroup($uid, $groupId);
    }

    /*
     * 禁用用户
     * $model 模块
     * $map条件
     */
    protected function forbid($model, $map){
        $data['status'] = 0;
        $res = M($model)->where($map)->data($data)->save();
        if($res){
//            action_log($data['id'],'用户被')
            $this->success('状态禁用成功');
        }else{
            $this->error('状态禁用失败');
        }
    }

    /*
     * 删除用户
     */
    protected function delete($model,$map){
        $res = M($model)->where($map)->delete();
        if($res){
            $this->success('用户删除成功');
        }else{
            $this->error('用户删除失败');
        }
    }

    /*
     * 启用用户
     */
    protected function resume($model,$map){
        $data['status'] =1;
        $res = M($model)->where($map)->data($data)->save();
        if($res){
            $this->success('启用用户成功');
        }else{
            $this->error('启用用户失败');
        }
    }

    /*
    * 用户退出
    */
    public function logout(){
        if(is_login()){
            D('User')->logout();
            action_log('user_logout','user',UID,UID);
            session('[destroy]');
            $this->success('退出成功！', U('login'));
        } else {
            $this->redirect('login');
        }
    }

    //用户修改密码
    public function changePwd(){
        if(IS_POST){
            $password = I('post.old');
            empty($password) && $this->error('请输入原始密码');
            if(!$this->checkpwd($password)){
                $this->error('原始密码输入不正确');
            }
            $data['password'] = I('post.pwd');
            empty($data['password']) && $this->error('请输入新密码');
            $repassword = I('post.repwd');
            empty($repassword) && $this->error('请输入确认密码');
            if($data['password'] !== $repassword){
                $this->error('两次输入的密码不一样');
            }
            $data['password'] = md5($data['password']);
            $user = new UserApi();
            $res= $user->updateInfo(UID, $data);
            if($res){
                action_log('user_changePassword','user',UID,UID);
                $this->success('密码已经修改成功',__APP__.'/Admin/User/logout');
            }else{
                $this->error('密码修改失败');
            }

        }else{
            $this->assign('meta_title','修改密码');
            $this->display();
        }
    }

    //检查密码输入的是否正确
    private function checkPwd($pwd){
        $map['id'] = UID;
        $check = M('User')->where($map)->getField('password');
        if($check === md5($pwd)){
            return true;
        }else{
            return false;
        }
    }

    //初始化用户密码
    public function initUser($id){
        $initPassword = "123456";
        $data = array(
            'password'=>md5($initPassword)
        );
        $user = M('User');
        $res  = $user->where('id='.$id)->find();
        if($res)
        {
            if($res['password'] == md5($initPassword))
            {
                $this->error('初始化密码不能和原先密码一样');
            }
            else
            {
                $result = $user->where('id='.$id)->save($data);
                if($result){
                    action_log('init_password','user',$id,UID);
                    $this->success('初始化密码成功');
                }else{
                    $this->error('初始化密码失败');
                }
            }
        }
        else
        {
            $this->error('用户不存在');
        }

    }

    //用户行为列表
    public function userAction(){
        $Action = M('Action')->where(array('status'=>array('gt',-1)));
        $list = $this->lists($Action);
        int_to_string($list);

        Cookie('__forward__',$_SERVER['REQUEST_URI']);

        $this->assign('_list', $list);
        $this->meta_title = '用户行为';
        if(isset($_GET['p'])){
            $num = ($_GET['p']-1)*10;
            $this->assign('num', $num);
        }
        $this->display();
    }

    //添加用户行为
    public function addAction(){
        $this->meta_title = '新增行为';
        $this->assign('data',null);
        $this->display('editAction');
    }

    //编辑用户行为
    public function editAction(){
        $id = I('get.id');
        if(empty($id)){
            $this->error('参数不能为空');
        }
        $info = M('Action')->field(true)->find($id);
        $this->assign('info',$info);
        $this->meta_title = '编辑行为';
        $this->display('editAction');
    }

    //更新用户行为
    public function saveAction(){
        $res = D('Action')->update();
        if(!$res){
            $this->error(D('Action')->getError());
        }else{
            $this->success($res['id']?'更新成功！':'新增成功！', Cookie('__forward__'));
        }
    }

    //机构用户查询
    public function unitIndex(){
        $where['title']=array('like','%机构管理员');
        $res=M('auth_group')->where($where)->find();//查找管理员
//        $array=M('user')->select();
//        foreach($array as $key=>$vo){
//            $arr[$vo['id']]=$vo;
//        }

        $id=I('id');//搜索的时候传id
        if($id){
            $res=M('department')->where(array('id'=>$id))->getField('uid',true);
            $where['id'] = array('in',implode(',',$res));
        }else{

            $map['group_id'] = $res['id'];

            $res = M('AuthGroupAccess')->where($map)->getField('uid', true);
            $where['id'] = array('in',implode(',',$res));
        }
         $where['department'] = array('gt',0);  //添加 条件
         $User =M('User');
         $list = $this->lists($User,$where);
         $this->assign('_list', $list);
         $this->assign('search_id', $id);//搜索框选中
//         $this->assign('arr',$arr);
         $this->display();
    }


    //机构用户信息
    public function unitUserInfo(){
        $type       = I('type');
        $id         = intval(I('id'));
        $user       = M('User');
        $u_list     = $user->find($id);
        if($u_list)
        {
            $u_list['categoryid'] = explode(',',$u_list[categoryid]);
            $this->assign('info', $u_list);
            $this->assign('category',C('TYPEID'));
            $this->assign('type',$type);
            $this->meta_title = '机构人员管理';
            $this->display();
        }
        else
        {
            $this->error('数据不存在');
        }
    }
    public function unitUseredit(){//机构人员修改
        if(IS_POST){
            $data=I('post.');
            $id           = intval(I('id'));
            $user         = M('User');
            $u_list       = $user->find($id);
            $arr['tel']   =$data['tel'];
            $arr['email'] =$data['email'];
            if($u_list)
            {
                $arr['id'] = $u_list['id'];
                $result = D('User')->update($arr);
                if($result>0){
                    $this->success("修改成功",U('User/unitIndex'));
                }else{
                    $this->error($this->showRegError($result));
                }
            }
            else
            {
                $this->error('数据不存在');
            }

        }else{
            $id         = intval(I('id'));
            $user       = M('User');
            $u_list     = $user->find($id);
            if($u_list)
            {
                $this->assign('info', $u_list);
                $this->meta_title = '机构人员管理';
                $this->display();
            }
            else
            {
                $this->error('数据不存在');
            }

        }
    }
    function getUser($list=array()){
        if(!empty($list)){
            $data = array();
            foreach($list as $k=>$v){
                $userModel = new UserModel();
                $data[] = $userModel->find($v['uid']);
            }
        }
        return $data;
    }
    private function showRegError($code = 0){
        switch ($code) {
            case -1:  $error = '用户名长度必须在16个字符以内！'; break;
            case -2:  $error = '用户名被禁止注册！'; break;
            case -3:  $error = '用户名被占用！'; break;
            case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
            case -5:  $error = '邮箱格式不正确！'; break;
            case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
            case -7:  $error = '邮箱被禁止注册！'; break;
            case -8:  $error = '邮箱被占用！'; break;
            case -9:  $error = '手机格式不正确！'; break;
            case -10: $error = '手机被禁止注册！'; break;
            case -11: $error = '手机号被占用！'; break;
            case -119: $error = '添加用户出错';break;
            case -13: $error = '保存失败';break;
            default:  $error = '未知错误';
        }
        return $error;
    }
}